import { watch } from './C:/Users/Administrator/AppData/Local/Microsoft/TypeScript/2.6/node_modules/@types/mz/fs';

'use stric';

const nunjucks = require('nunjucks');

/**
 * 生成 nunjucks 对象
 * @param {*} path thml模板路径
 * @param {*} opts nunjucks 配置
 */
const createEnv = (path, opts) => {
    var 
        autoescape = opts.autoescape === undefined ? true : opts.autoescape,
        noCache = opts.noCache || false,
        watch = opts.watch || fasle,
        throwOnUndefined = opts.throwOnUndefined || false,
        env = new nunjucks.Environment(
            new nunjucks.FileSystemLoader(path, {
                noCache,
                watch
            }), {
                autoescape,
                throwOnUndefined
            }
        )
        if (opts.filters) {
            for (var f in opts.filters) {
                env.addFilter(f, opts.filters[f]);
            }
        }
        return env
}

/**
 * 用 nunjucks 对象为 ctx 增加 render 函数
 * @param {*} path thml模板路径
 * @param {*} opts nunjucks 配置
 */
const templateing = (path, opts) => {
    var env = createEnv(path, opts);
    return async (ctx, next) => {
        ctx.render = (view, module) => {
            ctx.response.body = env.render(view, Object.assign({}, ctx.state || {}, module || {}));
            ctx.response.type = 'text/html';
        }
        await next();
    }
}

module.exports = templateing;